#include "include/ffmpeg.hpp"
#include "include/SimpleAVPacketSerializer.hpp"
#include "include/CodecParamsSerializer.hpp"
#include "include/TcpConnection.hpp"
#include "include/TLVPacket.hpp"
#include "include/businessService.hpp"
#include "include/TLV.hpp"
#include <vector>
using std::vector;
void print_av_packet(AVPacket* packet, AVFormatContext* fmt_ctx);

void print_av_packet(AVPacket* packet, AVFormatContext* fmt_ctx) {
    // 打印基本信息
    std::cout << "AVPacket Info:" << std::endl;
    std::cout << "  Size: " << packet->size << " bytes" << std::endl;
    std::cout << "  Stream index: " << packet->stream_index << std::endl;

    // 获取流类型
    AVMediaType type = fmt_ctx->streams[packet->stream_index]->codecpar->codec_type;
    const char* type_str = av_get_media_type_string(type);
    std::cout << "  Stream type: " << (type_str ? type_str : "Unknown") << std::endl;

    // 打印时间戳信息（包括转换为秒）
    std::cout << "  PTS: " << packet->pts;
    if (packet->pts != AV_NOPTS_VALUE) {
        AVStream *stream = fmt_ctx->streams[packet->stream_index];
        double pts_seconds = packet->pts * av_q2d(stream->time_base);
        std::cout << " (" << pts_seconds << " seconds)";
    }
    std::cout << std::endl;

    // 类似处理 DTS 和 duration...

    // 打印标志位
    std::cout << "  Flags: ";
    if (packet->flags & AV_PKT_FLAG_KEY) std::cout << "KEY ";
    if (packet->flags & AV_PKT_FLAG_CORRUPT) std::cout << "CORRUPT ";
    if (packet->flags & AV_PKT_FLAG_DISCARD) std::cout << "DISCARD ";
    std::cout << std::endl;

    // 打印数据前16字节的十六进制
    std::cout << "  Data (first 16 bytes): ";
    int bytes_to_print = std::min(16, packet->size);
    for (int i = 0; i < bytes_to_print; i++) {
        printf("%02X ", packet->data[i]);
    }
    std::cout << std::endl;
}


pair<string,string > RtspDecoder::recvAVCodecParameters(string url){
        cout << "FFmpegKits::run()...\n";
    AVFormatContext *pFormatCtx = nullptr;
    AVCodecParameters *pVideoCodecPar = nullptr;  // 视频编解码参数
    AVCodecParameters *pAudioCodecPar = nullptr;  // 音频编解码参数
    AVCodec *pVideoCodec = nullptr;
    AVCodec *pAudioCodec = nullptr;

    avformat_network_init();
    pFormatCtx = avformat_alloc_context();

    AVDictionary *avdic = nullptr;

    if (avformat_open_input(&pFormatCtx, url.data(), nullptr, &avdic) != 0) {
        cout << "can't open the file.\n";
        return pair<string,string>("","");
    }

    if (avformat_find_stream_info(pFormatCtx, nullptr) < 0) {
        cout << "Could't find stream information.\n";
        return pair<string,string>("","");
    }
    string value;
    // 查找视频流
    int videoStreamIdx = av_find_best_stream(pFormatCtx, AVMEDIA_TYPE_VIDEO, -1, -1, nullptr, 0);
    if (videoStreamIdx < 0) {
        cout << "av_find_best_stream error for video\n";
    } else {
        printf("video stream idx: %d\n", videoStreamIdx);
        pVideoCodecPar = pFormatCtx->streams[videoStreamIdx]->codecpar;
        vector<uint8_t> svalue =CodecParamsSerializer::serialize(pVideoCodecPar);
        value = string( (const char *)svalue.data(),svalue.size());
        //pVideoCodecPar = CodecParamsSerializer::deserialize((const uint8_t *)svalue.data(),svalue.size());
        pVideoCodec = avcodec_find_decoder(pVideoCodecPar->codec_id);
        if (pVideoCodec) {
            cout << "===== Video Codec Parameters =====" << endl;
            cout << "Codec ID: " << pVideoCodecPar->codec_id << endl;
            cout << "Width: " << pVideoCodecPar->width << endl;
            cout << "Height: " << pVideoCodecPar->height << endl;
            cout << "Pixel Format: " << pVideoCodecPar->format << endl;
            cout << "Bitrate: " << pVideoCodecPar->bit_rate << endl;
            cout << "Frame Rate: " << av_q2d(pFormatCtx->streams[videoStreamIdx]->avg_frame_rate) << " fps" << endl;
        } else {
            cout << "Video codec not found\n";
        }
    }
    // 查找音频流
    string audio_value;
    int audioStreamIdx = av_find_best_stream(pFormatCtx, AVMEDIA_TYPE_AUDIO, -1, -1, nullptr, 0);
    if (audioStreamIdx < 0) {
        cout << "av_find_best_stream error for audio\n";
    } else {
        printf("audio stream idx: %d\n", audioStreamIdx);
        pAudioCodecPar = pFormatCtx->streams[audioStreamIdx]->codecpar;
        pAudioCodec = avcodec_find_decoder(pAudioCodecPar->codec_id);
        vector<uint8_t> svalue =CodecParamsSerializer::serialize(pAudioCodecPar);
        audio_value = string( (const char *)svalue.data(),svalue.size());
        
        if (pAudioCodec) {
            cout << "===== Audio Codec Parameters =====" << endl;
            cout << "Codec ID: " << pAudioCodecPar->codec_id << endl;
            cout << "Sample Rate: " << pAudioCodecPar->sample_rate << " Hz" << endl;
            cout << "Channels: " << pAudioCodecPar->channels << endl;
            cout << "Channel Layout: " << pAudioCodecPar->channel_layout << endl;
            cout << "Sample Format: " << pAudioCodecPar->format << endl;
            cout << "Bitrate: " << pAudioCodecPar->bit_rate << endl;
            cout << "Frame Size: " << pAudioCodecPar->frame_size << endl;
        } else {
            cout << "Audio codec not found\n";
        }
    }
    // 资源清理
    avformat_close_input(&pFormatCtx);
    return pair<string,string>(value,audio_value);
}

void RtspDecoder::sendAVpacket(TcpConnection & _conn)
{
    cout << "FFmpegKits::run()...\n";
    AVFormatContext *pFormatCtx = nullptr;
    AVPacket *pPacket = nullptr;

    avformat_network_init();
    pFormatCtx = avformat_alloc_context();

    AVDictionary *avdic = nullptr;

    if(avformat_open_input(&pFormatCtx, _url.data(), nullptr, &avdic) != 0 ) {
        cout<<"url : "<<_url<<endl;
        cout << "can't open the file.\n";
        TLVPacket tlv(TASK_GET_AVPACKET_RESP_ERROR,string("url 错误请重新输入"));
        vector<uint8_t> msg = tlv.serialize();
        _conn.send(string((const char *)msg.data(),msg.size()));
        return;
    }

    if (avformat_find_stream_info(pFormatCtx, nullptr) < 0) {
        cout << "Could't find stream information.\n";
        return;
    }

    // 查找视频流
    int videoStreamIdx = av_find_best_stream(pFormatCtx, AVMEDIA_TYPE_VIDEO, -1, -1, nullptr, 0);
    if (videoStreamIdx < 0) {
        cout << "av_find_best_stream error for video\n";
    } else {
        printf("video stream idx: %d\n", videoStreamIdx);
    }

    // 查找音频流
    int audioStreamIdx = av_find_best_stream(pFormatCtx, AVMEDIA_TYPE_AUDIO, -1, -1, nullptr, 0);
    if (audioStreamIdx < 0) {
        cout << "av_find_best_stream error for audio\n";
    } else {
        printf("audio stream idx: %d\n", audioStreamIdx);
    }

    pPacket = av_packet_alloc();

    cout<<"address : "<<(void*)this<< endl;

    int cnt =0;
    _isContinue =true;
    while (_isContinue) {
        if (av_read_frame(pFormatCtx, pPacket) < 0) {
            break;
        }
        ++cnt;
        vector<uint8_t > value = SimpleAVPacketSerializer::serialize(*pPacket); 
        TLVPacket tlv(TASK_GET_AVPACKET_RESP_OK,string((const char *)value.data(),value.size()));
        vector <uint8_t> svalue = tlv.serialize();
        string msg((const char *) svalue.data(),svalue.size()); 
        _conn.send(msg);
        if (pPacket->stream_index == videoStreamIdx) {
            // 处理视频AVPacket
            /*cout << "Got video packet: "
                 << "size=" << pPacket->size
                 << ", pts=" << pPacket->pts
                 << ", dts=" << pPacket->dts
                 << ", duration=" << pPacket->duration
                 << endl;*/
            // 这里可以添加对视频包的处理逻辑
        }
        else if (pPacket->stream_index == audioStreamIdx) {
            // 处理音频AVPacket
           /* cout << "Got audio packet: "
                 << "size=" << pPacket->size
                 << ", pts=" << pPacket->pts
                 << ", dts=" << pPacket->dts
                 << ", duration=" << pPacket->duration
                 << endl;*/
            // 这里可以添加对音频包的处理逻辑
        }

        av_packet_unref(pPacket);
    }
    // 资源清理
    av_packet_free(&pPacket);
    avformat_close_input(&pFormatCtx);
}


const char * my_ts2str(int64_t t)
{
    static char buff[AV_TS_MAX_STRING_SIZE] = {0};
    av_ts_make_string(buff, t);
    return buff;
}

const char * my_ts2timestr(int64_t t, AVRational * tb)
{
    static char buff[AV_TS_MAX_STRING_SIZE] = {0};
    av_ts_make_time_string(buff, t, tb);
    return buff;
}

const char * my_err2str(int ret)
{
    static char buff[AV_ERROR_MAX_STRING_SIZE] = {0};
    av_make_error_string(buff, AV_ERROR_MAX_STRING_SIZE, ret);
    return buff;
}

static void log_packet(const AVFormatContext * fmt_ctx, const AVPacket * pkt, const char * tag)
{
    AVRational * time_base = &fmt_ctx->streams[pkt->stream_index]->time_base;
    printf("%s: pts:%s, pts_time:%s, dts:%s dts_time:%s, duration:%s dtime:%s index:%d\n",
            tag,
            my_ts2str(pkt->pts), my_ts2timestr(pkt->pts, time_base),
            my_ts2str(pkt->dts), my_ts2timestr(pkt->dts, time_base),
            my_ts2str(pkt->duration), my_ts2timestr(pkt->duration, time_base),
           pkt->stream_index);
}
void send_packet_with_sleep(AVFormatContext* fmt_ctx, AVPacket* pkt)
{
    // 1. 获取包对应的流
    AVStream* stream = fmt_ctx->streams[pkt->stream_index];

    // 2. 计算帧率
    double frame_rate = 0.0;

    if (stream->avg_frame_rate.den > 0 && stream->avg_frame_rate.num > 0) {
        // 使用平均帧率
        frame_rate = av_q2d(stream->avg_frame_rate);
    } else if (stream->r_frame_rate.den > 0 && stream->r_frame_rate.num > 0) {
        // 使用实时帧率
        frame_rate = av_q2d(stream->r_frame_rate);
    } else if (pkt->duration > 0 && stream->time_base.den > 0) {
        // 根据包持续时间计算帧率
        double frame_duration = pkt->duration * av_q2d(stream->time_base);
        if (frame_duration > 0) {
            frame_rate = 1.0 / frame_duration;
        }
    }

    // 3. 计算休眠时间（毫秒）
    long sleep_ms = 0;
    if (frame_rate > 0) {
        sleep_ms = static_cast<long>(1000.0 / frame_rate);
    } else {
        // 默认帧率（25fps）
        sleep_ms = 40;
    }

    // 4. 发送数据包（实际发送逻辑）
    // 这里替换为您的实际发送代码
    // send_to_destination(pkt);

    // 5. 打印调试信息
    //printf("Sending packet: stream %d, size %d, frame rate %.2f fps, sleeping %ld ms\n",
    //       pkt->stream_index, pkt->size, frame_rate, sleep_ms);

    // 6. 休眠对应时间
    std::this_thread::sleep_for(std::chrono::milliseconds(sleep_ms));
}

int RtspDecoder::read_partial_ts(TcpConnection & conn,const string & url, double max_duration, double tail_duration)
{
    const char * inFilename = url.c_str();
    AVPacket packet;
    int cnt = 0;
    double total_duration = 0.0;
    bool time_limit_reached = false;
    bool reading_tail = (tail_duration > 0);
    double start_time = 0.0;
    double end_time = 0.0;

    // 保存参数集
    uint8_t *sps_pps_data = nullptr;
    int sps_pps_size = 0;
    int video_stream_index = -1;
    double time_offset = 0.0;

    // 1. 打开TS文件
    AVFormatContext * inFmtCtx = nullptr;
    int ret = avformat_open_input(&inFmtCtx, inFilename, nullptr, nullptr);
    if(ret < 0) {
        fprintf(stderr, "avformat_open_input file %s error: %s\n",
                inFilename, my_err2str(ret));
        return EXIT_FAILURE;
    }

    // 2. 查找流媒体信息
    if((ret = avformat_find_stream_info(inFmtCtx, nullptr)) < 0) {
        fprintf(stderr, "avformat_find_stream_info error: %s\n", my_err2str(ret));
        avformat_close_input(&inFmtCtx);
        return EXIT_FAILURE;
    }

    // 3. 打印输入文件的媒体信息
    av_dump_format(inFmtCtx, -1, inFilename, 0);
    printf("\n======= Start reading packets =======\n");

    if (reading_tail) {
        printf("Reading tail: last %.2f seconds\n", tail_duration);
    } else if (max_duration > 0) {
        printf("Reading parameters: max_duration=%.2f seconds\n", max_duration);
    } else {
        printf("Reading entire file\n");
    }

    // 4. 查找视频流并保存参数集
    for (unsigned int i = 0; i < inFmtCtx->nb_streams; i++) {
        AVStream *stream = inFmtCtx->streams[i];
        if (stream->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
            video_stream_index = i;
            AVCodecParameters *par = stream->codecpar;
            if (par->extradata && par->extradata_size > 0) {
                sps_pps_size = par->extradata_size;
                sps_pps_data = (uint8_t*)av_malloc(sps_pps_size);
                memcpy(sps_pps_data, par->extradata, sps_pps_size);
                printf("Saved SPS/PPS: %d bytes\n", sps_pps_size);
            }

            // 获取第一个有效PTS作为时间偏移
            if (stream->start_time != AV_NOPTS_VALUE) {
                time_offset = stream->start_time * av_q2d(stream->time_base);
                printf("Time offset: %.2f seconds\n", time_offset);
            }
            break;
        }
    }

    // 5. 获取文件总时长
    double total_seconds = inFmtCtx->duration / (double)AV_TIME_BASE;
    printf("Total file duration: %.2f seconds\n", total_seconds);

    // 6. 如果是尾部读取，先定位到开始位置
    if (reading_tail) {
        // 计算开始时间点
        start_time = total_seconds - tail_duration;
        if (start_time < 0) start_time = 0;

        printf("Starting at %.2f seconds\n", start_time);

        // 转换为AV_TIME_BASE单位的时间戳
        int64_t seek_target = (int64_t)((start_time + time_offset) * AV_TIME_BASE);

        // 执行定位（向前定位到最近的关键帧）
        ret = av_seek_frame(inFmtCtx, -1, seek_target, AVSEEK_FLAG_BACKWARD);
        if (ret < 0) {
            fprintf(stderr, "Seek error: %s\n", my_err2str(ret));
            // 定位失败，但仍继续读取
        } else {
            printf("Seek successful to %.2f seconds\n", start_time);
        }

        // 设置结束时间为文件末尾
        end_time = total_seconds;
    } else if (max_duration > 0) {
        // 设置结束时间为最大持续时间
        end_time = max_duration;
    } else {
        // 读取整个文件
        end_time = total_seconds;
    }

    // 7. 创建解码器上下文（用于参数集注入）
    AVCodecContext *codec_ctx = nullptr;
    if (video_stream_index >= 0 && sps_pps_data && sps_pps_size > 0) {
        AVStream *stream = inFmtCtx->streams[video_stream_index];
        const AVCodec *codec = avcodec_find_decoder(stream->codecpar->codec_id);
        if (codec) {
            codec_ctx = avcodec_alloc_context3(codec);
            if (codec_ctx) {
                // 复制编解码器参数
                avcodec_parameters_to_context(codec_ctx, stream->codecpar);

                // 设置参数集
                codec_ctx->extradata = sps_pps_data;
                codec_ctx->extradata_size = sps_pps_size;

                // 打开解码器
                if (avcodec_open2(codec_ctx, codec, NULL) >= 0) {
                    printf("Decoder opened successfully with injected parameters\n");

                    // 重要：解码器上下文现在拥有extradata的所有权
                    // 设置sps_pps_data为nullptr避免双重释放
                    sps_pps_data = nullptr;
                } else {
                    fprintf(stderr, "Failed to open decoder\n");
                    avcodec_free_context(&codec_ctx);
                }
            }
        }
    }

    while(1) {
        if(_isContinue == false)break;
        // 8. 检查是否达到读取限制
        if (!reading_tail && max_duration > 0 && total_duration >= max_duration) {
            printf("Reached max duration: %.2f seconds\n", total_duration);
            time_limit_reached = true;
            break;
        }

        // 9. 读取一帧音视频压缩包
        ret = av_read_frame(inFmtCtx, &packet);
        if(ret < 0) {
            if (ret == AVERROR_EOF) {
                printf("End of file reached\n");
            } else {
                fprintf(stderr, "Read frame error: %s\n", my_err2str(ret));
            }
            break;
        }

        // 10. 计算包的时间信息
        double packet_duration = 0.0;
        double packet_start_time = 0.0;
        if (packet.stream_index == video_stream_index) {
            AVStream *stream = inFmtCtx->streams[packet.stream_index];
            if (packet.duration > 0 && stream->time_base.den > 0) {
                packet_duration = packet.duration * av_q2d(stream->time_base);
            }
            if (packet.pts != AV_NOPTS_VALUE) {
                packet_start_time = packet.pts * av_q2d(stream->time_base) - time_offset;
            }
        }

        // 11. 对于尾部读取，跳过定位点之前的数据
        if (reading_tail && packet_start_time < start_time) {
            av_packet_unref(&packet);
            continue;
        }
        vector<uint8_t> data = SimpleAVPacketSerializer::serialize(packet);
        TLVPacket tlv(TASK_GET_AVPACKET_RESP_OK,string((const char*)data.data(),data.size()));
        vector <uint8_t> svalue = tlv.serialize();
        string msg((const char *) svalue.data(),svalue.size()); 
        conn.send(msg);


        // 12. 更新总持续时间
        total_duration += packet_duration;

        // 13. 打印包信息
        //log_packet(inFmtCtx, &packet, "TS_PKT");
        //printf("Packet %d: start %.2fs, duration %.4fs, total %.2fs\n",
               //cnt, packet_start_time, packet_duration, total_duration);

        //根据帧率设置发包速度
        send_packet_with_sleep(inFmtCtx, &packet);
        // 14. 释放包资源
        av_packet_unref(&packet);
        cnt++;
    }

    // 15. 清理资源
    if (codec_ctx) {
        avcodec_close(codec_ctx);
        avcodec_free_context(&codec_ctx);
    }

    // 只有在解码器上下文没有接管的情况下才释放sps_pps_data
    if (sps_pps_data) {
        av_free(sps_pps_data);
    }

    avformat_close_input(&inFmtCtx);

    if (reading_tail) {
        printf("Tail read completed: %d packets, %.2f seconds\n", cnt, total_duration);
    } else if (time_limit_reached) {
        printf("Partial read completed: %d packets, %.2f seconds\n", cnt, total_duration);
    } else {
        printf("Full read completed: %d packets, %.2f seconds\n", cnt, total_duration);
    }

    return 0;



}

void RtspDecoder:: run(TcpConnection & conn, int camera_id,int channel,long start_time,long end_time){

    
        char sql[256]={0};
        sprintf(sql,"SELECT name,start_time,end_time FROM record_file   WHERE camera_id = %d AND start_time <= %ld AND end_time >= %ld AND channel = %d ORDER BY start_time",camera_id,end_time,start_time,channel);
        LOG_DEBUG(sql);
        MySQLClient SQLConn;
        vector<vector<string>> data = SQLConn.readOperationQuery(sql);
        SQLConn.dump(data);
        if(data.size()<2){
            char value[1]={0};
            TLV tlv(TASK_GET_AVPACKET_RESP_ERROR,0,value);
            string msg(reinterpret_cast<char *>(&tlv),8+0);
            conn.sendInLoop(msg);
        }
        SQLConn.dump(data);
        _isContinue =true;
        for(int i = 1;i < (int)data.size();++i){
            if(_isContinue == false) return;
            if(i == 1 ){
                double tail_duration = (std::atol(data[i][2].c_str())-start_time)/1000000;
                cout<<"tail_duration value is : "<<tail_duration<<endl;
                read_partial_ts(conn,data[i][0],0,tail_duration);
            }else if(i == ((int)data.size()-1)){
                double max_duration = (end_time-std::atol(data[i][1].c_str()))/1000000;
                cout<<"max_duration value is : "<<max_duration<<endl;
                read_partial_ts(conn,data[i][0],max_duration,0);
            }else{
                read_partial_ts(conn,data[i][0],0,0);
            }
        }

}


pair<string,string> RtspDecoder::get_playback_decoder_parameters(const string & url)
{
    const char * inFilename = url.c_str(); // 修改为你的TS文件路径
    
    // 1. 打开TS文件
    AVFormatContext * inFmtCtx = nullptr;
    int ret = avformat_open_input(&inFmtCtx, inFilename, nullptr, nullptr);
    if(ret < 0) {
        fprintf(stderr, "avformat_open_input file %s error: %s\n", 
                inFilename, my_err2str(ret));
        return pair<string,string>("","");
    }

    // 2. 查找流媒体信息
    if((ret = avformat_find_stream_info(inFmtCtx, nullptr)) < 0) {
        fprintf(stderr, "avformat_find_stream_info error: %s\n", my_err2str(ret));
        avformat_close_input(&inFmtCtx);
        return pair<string,string>("","");
    }

    // 3. 打印输入文件的媒体信息
    av_dump_format(inFmtCtx, -1, inFilename, 0);
    printf("\n======= Decoder Parameters =======\n");

    // 4. 遍历所有流并获取解码器参数
    AVFormatContext *pFormatCtx = inFmtCtx;
    AVCodecParameters *pVideoCodecPar = nullptr;  // 视频编解码参数
    AVCodecParameters *pAudioCodecPar = nullptr;  // 音频编解码参数
    AVCodec *pVideoCodec = nullptr;
    AVCodec *pAudioCodec = nullptr;
    string value;
    // 查找视频流
    int videoStreamIdx = av_find_best_stream(pFormatCtx, AVMEDIA_TYPE_VIDEO, -1, -1, nullptr, 0);
    if (videoStreamIdx < 0) {
        cout << "av_find_best_stream error for video\n";
    } else {
        printf("video stream idx: %d\n", videoStreamIdx);
        pVideoCodecPar = pFormatCtx->streams[videoStreamIdx]->codecpar;
        vector<uint8_t> svalue =CodecParamsSerializer::serialize(pVideoCodecPar);
        value = string( (const char *)svalue.data(),svalue.size());
        //pVideoCodecPar = CodecParamsSerializer::deserialize((const uint8_t *)svalue.data(),svalue.size());
        pVideoCodec = avcodec_find_decoder(pVideoCodecPar->codec_id);
        if (pVideoCodec) {
            cout << "===== Video Codec Parameters =====" << endl;
            cout << "Codec ID: " << pVideoCodecPar->codec_id << endl;
            cout << "Width: " << pVideoCodecPar->width << endl;
            cout << "Height: " << pVideoCodecPar->height << endl;
            cout << "Pixel Format: " << pVideoCodecPar->format << endl;
            cout << "Bitrate: " << pVideoCodecPar->bit_rate << endl;
            cout << "Frame Rate: " << av_q2d(pFormatCtx->streams[videoStreamIdx]->avg_frame_rate) << " fps" << endl;
        } else {
            cout << "Video codec not found\n";
        }
    }

    // 查找音频流
    string audio_value;
    int audioStreamIdx = av_find_best_stream(pFormatCtx, AVMEDIA_TYPE_AUDIO, -1, -1, nullptr, 0);
    if (audioStreamIdx < 0) {
        cout << "av_find_best_stream error for audio\n";
    } else {
        printf("audio stream idx: %d\n", audioStreamIdx);
        pAudioCodecPar = pFormatCtx->streams[audioStreamIdx]->codecpar;
        pAudioCodec = avcodec_find_decoder(pAudioCodecPar->codec_id);
        vector<uint8_t> svalue =CodecParamsSerializer::serialize(pAudioCodecPar);
        audio_value = string( (const char *)svalue.data(),svalue.size());
        
        if (pAudioCodec) {
            cout << "===== Audio Codec Parameters =====" << endl;
            cout << "Codec ID: " << pAudioCodecPar->codec_id << endl;
            cout << "Sample Rate: " << pAudioCodecPar->sample_rate << " Hz" << endl;
            cout << "Channels: " << pAudioCodecPar->channels << endl;
            cout << "Channel Layout: " << pAudioCodecPar->channel_layout << endl;
            cout << "Sample Format: " << pAudioCodecPar->format << endl;
            cout << "Bitrate: " << pAudioCodecPar->bit_rate << endl;
            cout << "Frame Size: " << pAudioCodecPar->frame_size << endl;
        } else {
            cout << "Audio codec not found\n";
        }
    }
    // 5. 清理资源
    avformat_close_input(&inFmtCtx);
    printf("\nFinished extracting decoder parameters\n");
//    return pair<string,string>("","");
    return pair<string,string>(value, audio_value);
}



